<template>
  <div ref="gameContainer" class="game-container">
    <!-- 分数显示 -->
    <div class="score-board">得分: {{ score }}</div>

    <!-- 水果 -->
    <div
      v-for="(fruit, index) in fruits"
      :key="index"
      class="fruit"
      :style="{
        left: fruit.x + 'px',
        top: fruit.y + 'px',
        backgroundImage: `url(${fruit.image})`
      }"
    ></div>

    <!-- 角色 -->
    <div class="character" :style="{ left: characterX - characterWidth / 2 + 'px' }"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'

/** 水果接口 */
interface Fruit {
  x: number
  y: number
  speed: number
  value: number
  image: string
}

const score = ref(0)
const characterX = ref(window.innerWidth / 2)
const fruits = ref<Fruit[]>([])
const gameContainer = ref<HTMLElement | null>(null)
const gameLoopId = ref<number>(0)

const fruitSize = 50
const characterWidth = 80
const characterY = window.innerHeight - 120

const fruitImages = [
  '/images/fruit/li.png',
  '/images/fruit/putao.png',
  '/images/fruit/xiangjiao.png',
  '/images/fruit/xigua.png',
  '/images/fruit/yingtao.png'
]

const collisionSounds = [
  '/audio/audio1.mp3',
  '/audio/fail.mp3',
  '/audio/audio.mp3',
  '/audio/good.mp3',
  '/audio/unbelivable.mp3'
]

/** 播放随机音效 */
const audioCache = collisionSounds.map((src) => new Audio(src))
const playRandomCollisionSound = () => {
  const randomIndex = Math.floor(Math.random() * audioCache.length)
  const sound = audioCache[randomIndex]
  sound.currentTime = 0 // 每次从头播
  sound.play()
}

/** 创建水果 */
const createFruit = () => {
  const coinValue = Math.floor(Math.random() * 10) + 1
  const startX = Math.random() * (window.innerWidth - fruitSize)

  fruits.value.push({
    x: startX,
    y: 0,
    speed: Math.random() * 3 + 2,
    value: coinValue,
    image: fruitImages[Math.floor(Math.random() * fruitImages.length)]
  })
}

/** 触摸控制（移动端） */
const handleTouchMove = (e: TouchEvent) => {
  characterX.value = e.touches[0].clientX
}

/** 窗口缩放处理 */
const handleResize = () => {
  characterX.value = Math.min(characterX.value, window.innerWidth - characterWidth / 2)
}

/** 键盘按下状态 */
const keys = ref<{ left: boolean; right: boolean }>({ left: false, right: false })

/** 键盘按下 */
const handleKeyDown = (e: KeyboardEvent) => {
  if (e.key === 'ArrowLeft') {
    keys.value.left = true
  } else if (e.key === 'ArrowRight') {
    keys.value.right = true
  }
}

/** 键盘松开 */
const handleKeyUp = (e: KeyboardEvent) => {
  if (e.key === 'ArrowLeft') {
    keys.value.left = false
  } else if (e.key === 'ArrowRight') {
    keys.value.right = false
  }
}

/** 游戏循环 */
/** 游戏循环 */
const gameLoop = () => {
  // ⬅️⬅️⬅️ 这里新增持续移动逻辑
  if (keys.value.left && characterX.value > characterWidth / 2) {
    characterX.value -= 5 // 移动速度（比原来的 20px 更平滑）
  }
  if (keys.value.right && characterX.value < window.innerWidth - characterWidth / 2) {
    characterX.value += 5
  }

  // ⬇️ 下面是原有水果逻辑
  for (let i = fruits.value.length - 1; i >= 0; i--) {
    const fruit = fruits.value[i]
    fruit.y += fruit.speed

    if (
      fruit.y + fruitSize > characterY &&
      fruit.x + fruitSize / 2 > characterX.value - characterWidth / 2 &&
      fruit.x + fruitSize / 2 < characterX.value + characterWidth / 2
    ) {
      playRandomCollisionSound()
      score.value += fruit.value
      fruits.value.splice(i, 1)
      continue
    }

    if (fruit.y > window.innerHeight) {
      fruits.value.splice(i, 1)
    }
  }

  if (Math.random() < 0.01 + score.value * 0.0005) {
    createFruit()
  }

  gameLoopId.value = requestAnimationFrame(gameLoop)
}
onMounted(() => {
  window.addEventListener('keydown', handleKeyDown)
  window.addEventListener('keyup', handleKeyUp) // 监听松开事件
  window.addEventListener('resize', handleResize)
  window.addEventListener('touchmove', handleTouchMove)

  gameLoopId.value = requestAnimationFrame(gameLoop)
})

onUnmounted(() => {
  window.removeEventListener('keydown', handleKeyDown)
  window.removeEventListener('keyup', handleKeyUp)
  window.removeEventListener('resize', handleResize)
  window.removeEventListener('touchmove', handleTouchMove)
  cancelAnimationFrame(gameLoopId.value)
})
</script>

<style scoped>
.game-container {
  position: relative;
  width: 100vw;
  height: 100vh;
  background: url('/images/caodi.jpg') no-repeat center/cover;
  overflow: hidden;
}

.score-board {
  position: absolute;
  top: 20px;
  left: 20px;
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.fruit {
  position: absolute;
  width: 200px;
  height: 200px;
  background-size: cover;
  background-position: center;
}

.character {
  position: absolute;
  bottom: 20px;
  width: 80px;
  height: 80px;
  background: url('/images/maliao.png') no-repeat center/contain;
}
.fruit {
  position: absolute;
  width: 50px;
  height: 50px;
  background-size: cover;
  background-position: center;
  text-align: center;
  line-height: 50px;
  font-weight: bold;
  color: gold;
  font-size: 18px;
  text-shadow: 1px 1px 2px #000;
}

.score-board {
  position: absolute;
  top: 20px;
  left: 20px;
  font-size: 24px;
  font-weight: bold;
  color: #fff;
  background: rgba(0, 0, 0, 0.5);
  padding: 8px 16px;
  border-radius: 8px;
}
</style>
